package com.example.pmanagesys.controller;

import com.example.pmanagesys.entity.ExcelExportRequest;
import com.example.pmanagesys.entity.SalaryInquiry;
import com.example.pmanagesys.mapper.SalaryInquiryMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/salary")
public class SalaryInquiryControlly {

    //  工资查询 页面
    @GetMapping("/file")
    public ModelAndView home() {
        return new ModelAndView("SalaryInquiry");
    }

    @Autowired
    private SalaryInquiryMapper salaryInquiryMapper;


    //  分页查询  http://localhost:8080/salary/page?pageNum=1&pageSize=15&z_name=&month=
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                        @RequestParam String z_name, @RequestParam String month) {
        // 模糊查询的参数 (可以为空）
        z_name = "%" + z_name + "%";
        month = "%" + month + "%";
        // 某一页的数据
        pageNum = (pageNum - 1) * pageSize;
        List<SalaryInquiry> data = salaryInquiryMapper.selectPage(pageNum, pageSize, z_name, month);
        // 总条数
        Integer total = salaryInquiryMapper.selectTotal(z_name, month);
        // 封装一个map装数据
        Map<String, Object> res = new HashMap<>();
        res.put("salaryData", data);
        res.put("total", total);
        return res;
    }

    /** 导出接口 */
    @PostMapping("/export")
    public ResponseEntity<byte[]> exportExcel(@RequestBody ExcelExportRequest request) {
        try {
            Map<String, String> headerMap = request.getHeaderMap();
            List<Map<String, Object>> rows = request.getRows();
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表
            Sheet sheet = workbook.createSheet("Sheet1");
            // 创建表头行
            Row headerRow = sheet.createRow(0);
            // 设置表头单元格样式
            CellStyle headerCellStyle = workbook.createCellStyle();
            headerCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            // 创建表头单元格
            int columnIndex = 0;
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                Cell cell = headerRow.createCell(columnIndex++);
                cell.setCellValue(entry.getValue());
                // 不设置单元格样式，使用默认样式
                // cell.setCellStyle(headerCellStyle);
            }
            // 创建数据行
            int rowIndex = 1;
            for (Map<String, Object> row : rows) {
                Row dataRow = sheet.createRow(rowIndex++);
                columnIndex = 0;
                for (Map.Entry<String, Object> entry : row.entrySet()) {
                    Cell cell = dataRow.createCell(columnIndex++);
                    cell.setCellValue(entry.getValue().toString());
                }
            }
            // 将 Excel 数据写入字节数组输出流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "工资明细.xlsx");
            // 返回 Excel 文件的字节数组 给前端，前端再处理
            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace(); // 或者处理异常的逻辑
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
